import { http } from "@/utils/http";

export type LoginRequest = {
  username: string;
  password: string;
};

export type RegisterRequest = {
  username: string;
  password: string;
  email?: string;
  nickname?: string;
};

export type Admin = {
  id: number;
  username: string;
  email?: string;
  nickname?: string;
  avatar?: string;
  status: number;
  disabled: boolean;
  created_at: string;
  updated_at: string;
  deleted_at?: string;
};

export type LoginResponse = {
  success: boolean;
  code: number;
  message: string;
  data: Admin;
  token: string;
};

export type RegisterResponse = {
  success: boolean;
  code: number;
  message: string;
  data: Admin;
};

export type UserInfoResult = {
  success: boolean;
  code: number;
  message: string;
  data: Admin;
};

export type RefreshTokenResult = {
  success: boolean;
  code: number;
  message: string;
  data: {
    accessToken: string;
    refreshToken: string;
    expires: string;
  };
};

export type SecurityLog = {
  id: number;
  summary: string;
  ip: string;
  address: string;
  system: string;
  browser: string;
  operatingTime: string;
};

export type SecurityLogsResult = {
  success: boolean;
  code: number;
  message: string;
  data: {
    list: SecurityLog[];
    total: number;
    pageSize: number;
    currentPage: number;
  };
};

export type AdminListResponse = {
  success: boolean;
  code: number;
  message: string;
  data: Admin[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_page: number;
  };
};

export type PaginationParams = {
  page?: number;
  page_size?: number;
};

/** 登录 */
export const getLogin = (data: LoginRequest) => {
  return http.request<LoginResponse>("post", "/admin/login", { data });
};

/** 注册 */
export const registerAdmin = (data: RegisterRequest) => {
  return http.request<RegisterResponse>("post", "/admin/register", { data });
};

/** 获取当前用户信息 */
export const getProfile = () => {
  return http.request<UserInfoResult>("get", "/admin/profile");
};

/** 更新当前用户信息 */
export const updateProfile = (data: Partial<Admin>) => {
  return http.request<UserInfoResult>("put", "/admin/profile", { data });
};

/** 获取管理员列表 */
export const getAdmins = (params?: PaginationParams) => {
  return http.request<AdminListResponse>("get", "/admin", { params });
};

/** 获取管理员详情 */
export const getAdminById = (id: number) => {
  return http.request<UserInfoResult>("get", `/admin/${id}`);
};

/** 删除管理员 */
export const deleteAdmin = (id: number) => {
  return http.request("delete", `/admin/${id}`);
};

/** 刷新token */
export const refreshTokenApi = (data: any) => {
  return http.request<RefreshTokenResult>("post", "/admin/refresh", { data });
};

/** 获取当前用户信息（用于账户设置） */
export const getMine = () => {
  return http.request<UserInfoResult>("get", "/admin/profile");
};

/** 获取当前用户的安全日志 */
export const getMineLogs = () => {
  return http.request<SecurityLogsResult>("get", "/admin/logs");
};